import React, { Component } from 'react';
import { Chart, Tooltip, Geom, Coord, Axis } from 'bizcharts';
import { Row, Col, Icon } from 'antd';
import autoHeight from '../autoHeight';
import styles from './index.less';

/* eslint react/no-danger:0 */
@autoHeight()
export default class Radar extends Component {
  state = {
    legendData: [],
    
  };

  componentDidMount() {
    this.getLengendData();
  }

  
  componentWillReceiveProps(nextProps) {
    
    //console.log('!!!4 nextProps', nextProps, ' this.props.activekey',  this.props.activekey, ' nextProps.activekey',  nextProps.activekey)
    if (this.props.data !== nextProps.data || this.props.activekey !== nextProps.activekey) {
      this.getLengendData(nextProps.activekey);
      // if(this.props.activekey){    
        // const activekey = this.props.activekey
        // const legendData = this.state.legendData
        // this.chart.filter('name', val => val == activekey);
        // for(let i in legendData){
        //   if(legendData[i].name !== activekey){
        //     const newItem = legendData[i]
        //     newItem.checked = false
        //     legendData[i] = newItem
        //     console.log('!!!~ set legendData 1')
        //   }
        // }
        // this.setState({legendData}) 
      // }
    }
  }

  getG2Instance = chart => {
    this.chart = chart;
   // console.log('chart111111',chart)
  };

  componentWillUpdate(nextProps, nextState){
  //  console.log('nextState11111', nextState)
    if(nextState.legendData && nextState.legendData.length != 12){
   
    }
  
  }


  // for custom lengend view
  getLengendData = (activekey) => {
    
    if (!this.chart) return;
    const geom = this.chart.getAllGeoms()[0]; // 获取所有的图形
    const items = geom.get('dataArray') || []; // 获取图形对应的
    //debugger;
    const legendData = items.map(item => {
      // eslint-disable-next-line
      const origins = item.map(t => t._origin);
      const result = {
        name: origins[0].name,
        color: item[0].color,
        // checked: false,
        checked: true,
        value: origins.reduce((p, n) => p + n.value, 0),
      };
      return result;
    });
    if(activekey){
        // this.chart.filter('name', val => val == activekey);
        for(let i in legendData){
          if(legendData[i].name !== activekey){
            legendData[i].checked = false
           // console.log('!!!~ set legendData 1')
          }
        }
    }
    // console.log('!!!~ set legendData 2')
    // console.log('!!! this.chart.getAllGeoms()[0];', this.chart.getAllGeoms()[0].get('dataArray'))
    //;
    var timmer = geom.get('dataArray') ? setInterval(()=>{
      if(geom.get('dataArray')){
        //console.log('~~~')
        clearInterval(timmer);
        const items = geom.get('dataArray') || []; // 获取图形对应的
        let legendData = items.map(item => {
          // eslint-disable-next-line
          const origins = item.map(t => t._origin);
          const result = {
            name: origins[0].name,
            color: item[0].color,
            //checked: false,
            checked: true,
            value: origins.reduce((p, n) => p + n.value, 0),
          };
          return result;
          
        });
        if(legendData.length < this.state.legendData.length){
          legendData = JSON.parse(JSON.stringify(this.state.legendData));
          legendData.forEach(item=>{
            if(item.name == activekey){
              item.checked = true;
            }else{
              item.checked = false;
            }
          })
        }
        if(activekey){
          // this.chart.filter('name', val => val == activekey);
          for(let i in legendData){
            if(legendData[i].name !== activekey){
              legendData[i].checked = false
          //    console.log('!!!~ set legendData 1')
          
            }
            
          }
      }

  
      if (this.chart) {
        // let tmp = JSON.parse(JSON.stringify(legendData)); // 复制一份原有数据，不被更改
        
        const filteredLegendData = legendData.filter(l => l.checked).map(l => l.name);
        this.chart.filter('name', val => filteredLegendData.indexOf(val) > -1);
        
        this.chart.repaint();
      }
  
        this.setState({
          legendData,
        });
      }
    }, 1e3) : null;

    this.setState({
      legendData,
    });
    
  };

  cutstr = (str, len) => {
    var str_length = 0;
    var str_len = 0;
    var str_cut = new String();
    str_len = str.length;
    for (var i = 0; i < str_len; i++) {
      var a = str.charAt(i);
      str_length++;
      if (escape(a).length > 4) {
        //中文字符的长度经编码之后大于4
        str_length++;
      }
      str_cut = str_cut.concat(a);
      if (str_length >= len) {
        str_cut = str_cut.concat('...');
        return str_cut;
      }
    }
    //如果给定字符串小于指定长度，则返回源字符串；
    if (str_length < len) {
      return str;
    }
  };

  handleRef = n => {
    this.node = n;
  };

  handleLegendClick = (item, i) => {

    
    const newItem = item;
    newItem.checked = !newItem.checked;

    const { legendData } = this.state;
    legendData[i] = newItem;

    const filteredLegendData = legendData.filter(l => l.checked).map(l => l.name);

    if (this.chart) {
      this.chart.filter('name', val => filteredLegendData.indexOf(val) > -1);
      this.chart.repaint();
    }
    this.setState({
      legendData,
    });
  };

  render() {
    const defaultColors = [
      '#1890FF',
      '#FACC14',
      '#2FC25B',
      '#8543E0',
      '#F04864',
      '#13C2C2',
      '#fa8c16',
      '#a0d911',
      '#00FF7F',
      '#20B2AA',
      '#4B0082',
      '#DDA0DD',
    ];

    const {
      data = [],
      height = '',
      title = '',
      hasLegend = false,
      forceFit = true,
      tickCount = 4,
      padding = [35, 45, 30, 30],
      animate = true,
      colors = defaultColors,
    } = this.props;

    const { legendData } = this.state;

    const scale = {
      value: {
        min: 0,
        tickCount,
      },
    };

    const chartHeight = height - (hasLegend ? 80 : 22);
    return (
      <Row>
        <Col className={styles.radarCol}>
          {title && <h4>{title}</h4>}
          <div className={styles.radar} style={{ height }}>
            <Chart
              scale={scale}
              height={chartHeight}
              forceFit={forceFit}
              data={data}
              padding={padding}
              animate={animate}
              onGetG2Instance={this.getG2Instance}
            >
              <Tooltip />
              <Coord type="polar" />
              <Axis
                name="label"
                line={null}
                tickLine={null}
                grid={{
                  lineStyle: {
                    lineDash: null,
                  },
                  hideFirstLine: false,
                }}
              />
              <Axis
                name="value"
                grid={{
                  type: 'polygon',
                  lineStyle: {
                    lineDash: null,
                  },
                }}
              />
              <Geom type="line" position="label*value" color={['name', colors]} size={1} />
              <Geom
                type="point"
                position="label*value"
                color={['name', colors]}
                shape="circle"
                size={2}
              />
            </Chart>
          </div>
        </Col>
        <Col className={styles.legendCol}>
          <div className={styles.radar} style={{ height }}>
            {hasLegend && (
              <Row className={styles.legend}>
                {legendData.map((item, i) => (
                  <Col
                    className={styles.legendItemCol}
                    span={24 / legendData.length}
                    key={item.name}
                    onClick={() =>{
                      this.handleLegendClick(item, i)
                    } }
                  >
                    <div className={styles.legendItem}>
                      <p>
                        <span
                          className={styles.dot}
                          style={{
                            backgroundColor: !item.checked ? '#aaa' : item.color,
                          }}
                        />
                        {/* <span className={styles.itemName}>{item.name}</span> */}
                        <span title={item.name} className={styles.itemName}>
                        {console.log('@@@',item.name)}
                          {this.cutstr(item.name, '8')}
                        </span>
                      </p>
                      <h6>{item.value}</h6>
                    </div>
                  </Col>
                ))}
              </Row>
            )}
          </div>
        </Col>
      </Row>
    );
  }
}
